package com.example.springbootmqdemo.aajuc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * JUC并发编程练习
 *
 * @Author: Jam
 * @Create 2022/12/2 - 18:34
 * @Version  使用Lock
 */
public class Thread2 {
    public static void main(String[] args) {
        TicketA ticket2  = new TicketA();

        //lambda表达式 (参数)->{代码}
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket2.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket2.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket2.sale();
            }
        }, "C").start();
    }
}
//1. new  ReentrantLock()
//2. lock.lock();//加锁
//3.  try/catch  finally 块
//4.  lock.unlock();//解锁
class TicketA{
    //属性 方法
    private  int number = 30;

    Lock lock = new ReentrantLock();

    //卖票
    public  void sale(){

        lock.lock();//加锁

        try {
            //业务代码
            if(number > 0){
                System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票，剩余："+number);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }finally {
            lock.unlock();//解锁
        }
    }
}